const API_BASE = 'http://localhost:3001/api';

// Token管理类
class AuthManager {
    private refreshPromise: Promise<string> | null = null;

    // 获取访问令牌
    getAccessToken(): string | null {
        // 优先返回 accessToken，如果没有则返回 token
        return localStorage.getItem('accessToken') || localStorage.getItem('token');
    }

    // 获取刷新令牌
    getRefreshToken(): string | null {
        return localStorage.getItem('refreshToken');
    }

    // 获取用户信息
    getUser(): any | null {
        const userStr = localStorage.getItem('user');
        return userStr ? JSON.parse(userStr) : null;
    }

    // 检查token是否过期
    isTokenExpired(): boolean {
        const expiresStr = localStorage.getItem('tokenExpires');
        if (!expiresStr) return true;

        const expires = parseInt(expiresStr);
        return Date.now() >= expires;
    }

    // 刷新访问令牌
    async refreshAccessToken(): Promise<string> {
        // 如果已经有刷新请求在进行中，直接返回该Promise
        if (this.refreshPromise) {
            return this.refreshPromise;
        }

        const refreshToken = this.getRefreshToken();
        if (!refreshToken) {
            throw new Error('No refresh token available');
        }

        this.refreshPromise = this.performRefresh(refreshToken);

        try {
            const newAccessToken = await this.refreshPromise;
            return newAccessToken;
        } finally {
            this.refreshPromise = null;
        }
    }

    private async performRefresh(refreshToken: string): Promise<string> {
        try {
            const response = await fetch(`${API_BASE}/auth/refresh`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ refreshToken }),
            });

            const data = await response.json();

            if (response.ok && data.success) {
                // 更新访问令牌和过期时间
                localStorage.setItem('accessToken', data.accessToken);
                localStorage.setItem('tokenExpires', (Date.now() + data.expiresIn).toString());
                return data.accessToken;
            } else {
                throw new Error(data.error || 'Token refresh failed');
            }
        } catch (error) {
            console.error('Token refresh failed:', error);
            // 刷新失败，清除所有认证信息
            this.clearAuth();
            throw error;
        }
    }

    // 获取有效的访问令牌（自动刷新）
    async getValidAccessToken(): Promise<string | null> {
        const accessToken = this.getAccessToken();

        if (!accessToken) {
            return null;
        }

        // 如果token即将过期（提前5分钟刷新），尝试刷新
        const expiresStr = localStorage.getItem('tokenExpires');
        if (expiresStr) {
            const expires = parseInt(expiresStr);
            const timeUntilExpiry = expires - Date.now();
            const fiveMinutes = 5 * 60 * 1000; // 5分钟

            if (timeUntilExpiry <= fiveMinutes) {
                try {
                    return await this.refreshAccessToken();
                } catch (error) {
                    console.error('Failed to refresh token:', error);
                    return null;
                }
            }
        }

        return accessToken;
    }

    // 设置认证信息
    setAuth(accessToken: string, refreshToken: string, expiresIn: number, user: any) {
        localStorage.setItem('accessToken', accessToken);
        localStorage.setItem('refreshToken', refreshToken);
        localStorage.setItem('tokenExpires', (Date.now() + expiresIn).toString());
        localStorage.setItem('user', JSON.stringify(user));
    }

    // 清除认证信息
    clearAuth() {
        localStorage.removeItem('accessToken');
        localStorage.removeItem('refreshToken');
        localStorage.removeItem('tokenExpires');
        localStorage.removeItem('token'); // 也清除兼容的token
        localStorage.removeItem('user');
    }

    // 检查是否已登录
    isAuthenticated(): boolean {
        // 检查 accessToken 或 token 或 user 信息
        const accessToken = this.getAccessToken();
        const token = localStorage.getItem('token');
        const user = this.getUser();

        // 如果有 accessToken 或 token，且不过期（或没有过期时间），且有用用户信息，则认为已登录
        const hasToken = !!(accessToken || token);
        const hasUser = !!user;

        // 如果有 token 但没有过期时间，也认为有效（简化逻辑）
        if (hasToken && hasUser) {
            const expiresStr = localStorage.getItem('tokenExpires');
            if (expiresStr) {
                const expires = parseInt(expiresStr);
                if (!isNaN(expires) && Date.now() >= expires) {
                    return false; // token已过期
                }
            }
            return true;
        }

        return false;
    }

    // 登出
    async logout() {
        try {
            const refreshToken = this.getRefreshToken();
            if (refreshToken) {
                await fetch(`${API_BASE}/auth/logout`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ refreshToken }),
                });
            }
        } catch (error) {
            console.error('Logout request failed:', error);
        } finally {
            this.clearAuth();
        }
    }

    // 创建带认证的请求头
    async getAuthHeaders(): Promise<Record<string, string>> {
        const token = await this.getValidAccessToken();
        return token ? { 'Authorization': `Bearer ${token}` } : {};
    }
}

// 导出单例实例
export const authManager = new AuthManager();
export default authManager;
